package com.fulin.datastract.huisu;

/**
 * @Description 8皇后问题
 * @Author fulin16
 * @Date 2020/9/26 9:53
 **/
public class EightQueue {
    private static int size = 0;

    private int[] result = new int[8];

    public static void main(String[] args) {
        EightQueue eight = new EightQueue();
        eight.call(0);
    }

    private void call(int row){
        if(row == 8){
            printQueue();
        }

        for(int column = 1;column <= 8; ++ column){
            if(ok(row,column)){
                result[row] = column;
                call(row +1);
            }
        }
    }

    private void printQueue() {
        size ++;
        for(int row = 0; row < 8 ; row ++){
            for(int column = 1; column < 9 ; column ++){
                if(result[row] == column){
                    System.out.print("Q  ");
                }else{
                    System.out.print("*  ");
                }
            }
            System.out.println();
        }
        System.out.println(size);
    }

    private boolean ok(int row,int column) {
        int upRow = row -1, leftColumn = column -1,rightColumn = column + 1;
        for(int i = upRow;i >= 0; --i){
            if(result[upRow] == column) return false;
            if(leftColumn > 0){
                if(result[upRow] == leftColumn) return false;
            }
            if(rightColumn < 9){
                if(result[upRow] == rightColumn) return false;
            }
            upRow --; leftColumn --; rightColumn ++;
        }
        return true;
    }
}
